<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ali;
use app\common\library\EpayCore;
use app\common\library\Wechat;
use app\common\model\Config;
use app\common\model\pay\Order;
use app\common\model\pay\Type;
use app\common\model\pay\type\Lists;
use think\Db;
use think\Exception;

class Pay extends Api
{
    protected $noNeedLogin = "lists";
    protected $noNeedRight = "*";

    public function lists()
    {
        $this->success("", Type::field("id,price,money")->select());
    }

    public function epay()
    {
        $id = $this->request->param("id", 0);
        $price = $this->request->param("price", 0);
        $type = $this->request->param("type");//alipay 支付宝 wxpay微信支付
        if (!$type) {
            $this->error("选择支付方式后操作");
        }
        if ($id == 0) {
//            if (!is_int($price)) {
//                $this->error("请充值整数");
//            }
            $ratio = Config::where(['group' => 'vipuser', 'name' => 'pay_ratio'])->value('value');
            $money = bcmul($price, $ratio, 2);
        } else {
            $types = Db::name('pay_type_lists')->where(['id' => $id])->find();
            $price = $types['price'];
            $money = $types['money'];
        }

        $order_sn = get_sn($this->auth->id);
        Db::startTrans();
        try {
            $order_insert['order_sn'] = $order_sn;
            $order_insert['user_id'] = $this->auth->id;
            $order_insert['price'] = $price;
            $order_insert['money'] = $money;
            $order_insert['pay_type_id'] = $id;
            Order::create($order_insert);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $notify_url = $this->request->domain() . "/api/notify/juhe";

        $parameter = array(
            "pid" => "1402",
            "type" => $type,
            "notify_url" => $notify_url,
            "return_url" => "",
            "out_trade_no" => $order_sn,
            "name" => "会员充值余额",
            "money" => $price,
            "clientip" => $this->request->ip()
        );

        try {
            $epay = new EpayCore([
                "pid" => "1402",
                "apiurl" => "https://pays.shenghaihao.com/",
                "key" => "mDC1IteMZm00EMCQ100CdcezVvDcskqs"
            ]);
            $array = $epay->apiPay($parameter);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        if ($array['code'] != 1) {
            $this->error($array['msg']);
        }
        $this->success("充值成功", $array);

    }

    public function order()
    {
        $id = $this->request->param("id", 0);
        $price = $this->request->param("price", 0);
        $type = $this->request->param("type");
        if (!$type) {
            $this->error("选择支付方式后操作");
        }
        if ($id == 0) {
            if (!is_int($price)) {
                $this->error("请充值整数");
            }
            $ratio = Config::where(['group' => 'vipuser', 'name' => 'pay_ratio'])->value('value');
            $money = bcmul($price * $ratio, 2);
        } else {
            $type = Type::get($id);
            $price = $type['price'];
            $money = round($type['money'], 2);
        }


        $order_sn = get_sn($this->auth->id);
        $notify_url = $this->request->domain() . "/api/notify/";
        try {
            switch ($type) {
                case 1:
                    $app = Wechat::app();
                    $result = $app->order->unify([
                        'body' => '会员余额-余额充值',
                        'out_trade_no' => $order_sn,
                        'total_fee' => bcmul($price, 100, 0),
//                        'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                        'notify_url' => $notify_url . "wechat_pay", // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                        'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                        'openid' => $this->auth->openid,
                    ]);
                    break;
                case 2:
                    $app = Ali::app();
                    $result = $app->faceToFace()
                        ->asyncNotify($notify_url . "ali_pay")//异步通知URL
                        ->preCreate("充值余额", $order_sn, round($price, 2));
                    if (empty($result->code) || $result->code != 10000) {
                        $this->error("调用失败，原因：" . $result->msg . "，" . $result->sub_msg . PHP_EOL);
                    }
                    break;
                default:
                    $this->error("当前支付方式有误");
                    break;
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

        Db::startTrans();
        try {
            $order_insert['order_sn'] = $order_sn;
            $order_insert['user_id'] = $this->auth->id;
            $order_insert['price'] = $price;
            $order_insert['money'] = $money;
            $order_insert['pay_type_id'] = $id;
            Order::create($order_insert);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success("", $result);
    }
}